package com.beiye.drivertransport.SubActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.bean.CompareFaceBean;
import com.beiye.drivertransport.bean.UpPhotoBean;
import com.beiye.drivertransport.bean.WriterBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.thirdparty.oss.OSSUpFileListener;
import com.beiye.drivertransport.utils.HelpUtil;
import com.beiye.drivertransport.utils.ImageUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.view.ChangeView;
import com.sandrios.sandriosCamera.internal.SandriosCamera;
import com.sandrios.sandriosCamera.internal.configuration.CameraConfiguration;
import com.sandrios.sandriosCamera.internal.manager.CameraOutputModel;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//驾驶员违章学习上传照片
public class TakePhotoIllegallearningActivity extends AppCompatActivity {

    private int screenWidth;
    private int screenHeight;
    private Integer uvtSn;
    private String snapTime;
    private String userId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo_illegallearning);

        Bundle bundle = getIntent().getExtras();
        uvtSn = bundle.getInt("uvtSn");
        snapTime = bundle.getString("snapTime");
        userId = bundle.getString("userId");


        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);// 取得窗口属性
        // 窗口的宽度
        screenWidth = dm.widthPixels;
        // 窗口高度
        screenHeight = dm.heightPixels;
        ViewGroup viewGroup=(ViewGroup)this.findViewById(android.R.id.content);
        ChangeView.changeViewSize(viewGroup, screenWidth, screenHeight);
        SharedPreferences sp = getSharedPreferences("TAG",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("TAG", 2);
        editor.commit();
        SandriosCamera
                .with(TakePhotoIllegallearningActivity.this)
                .setShowPicker(false)
                .setShowPickerType(CameraConfiguration.VIDEO)
                .setVideoFileSize(20)
                .setMediaAction(CameraConfiguration.MEDIA_ACTION_BOTH)
                .enableImageCropping(false)
                .launchCamera(new SandriosCamera.CameraCallback() {
                    @Override
                    public void onComplete(CameraOutputModel model) {
//                                LogUtils.e("File", "" + model.getPath());
//                                LogUtils.e("Type", "" + model.getType());
                        String url = model.getPath();
                        File file = new File(url);
                        LogUtils.e("测试", "onComplete1: "+file.length() );
                        try {
                            FileInputStream fis = new FileInputStream(file);
                            Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
                            bitmapByUrl = compressScale(bitmapByUrl);
                            SharedPreferences sp = getSharedPreferences("CameraSwitchView",
                                    Context.MODE_PRIVATE);
                            int action = sp.getInt("action", 0);
                            if(action==0)
                            {
                                bitmapByUrl = rotaingImageView(-90, bitmapByUrl);
                            }else if(action==1)
                            {
                                bitmapByUrl = rotaingImageView(90, bitmapByUrl);
                            }
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
                            Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间
                            String str = formatter.format(curDate);

                            Bitmap bitmap = ImageUtil.drawTextToRightBottom(TakePhotoIllegallearningActivity.this, bitmapByUrl, str,ChangeView.adjustFontSize(screenWidth, screenHeight), getResources().getColor(R.color.organger), 5, 5);
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                            bos.flush();
                            bos.close();
                            LogUtils.e("测试", "onComplete2: "+file.length() );
                            returnResult(file);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {

                        }


                    }
                });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SharedPreferences sp = getSharedPreferences("CameraSwitchView",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();

        SandriosCamera.sandriosCameraClear();
    }
    private void returnResult(File file) {
        Uri uri = Uri.fromFile(file);
        String url = uri.toString().substring(uri.toString().indexOf("///") + 2);
        uploadFile(TakePhotoIllegallearningActivity.this,file,0,url);


        Intent intent = new Intent();
        // 设置要回传的数据
        intent.putExtra("url", url);

        // 设置回传码和Intent
        setResult(1, intent);
        finish();
        //uploadImg(file,url);
    }
    /*private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();
    private void uploadImg(File mediaFile,final String url) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (mediaFile != null) {
            builder.addFormDataPart("headImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("uvtcSn",uvtSn.toString());
            builder.addFormDataPart("snapTime",snapTime);
            builder.addFormDataPart("userId",userId);

        }
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "app/course/uploadVoidImg")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //       LogUtils.e("上传失败", e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                String data = upPhotoBean.getData();
                boolean result = upPhotoBean.isResult();
                if(result)
                {
                    EventBus.getDefault().post(new MessageEvent(true,data,url));

                }else{
                    LogUtils.e("上传空值", data);
                    EventBus.getDefault().post(new MessageEvent(false,data,url));
                }

//                UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
//                String data = upPhotoBean.getData();
//                SharedPreferences sp = getSharedPreferences("imgurl",
//                        Context.MODE_PRIVATE);
//                //               String imgurl = sp.getString("imgurl", "");
//                SharedPreferences.Editor editor = sp.edit();
//                editor.putString("imgurl", data);
//                editor.commit();
//                if(imgurl.equals(""))
//                {
//                    editor.putString("imgurl", data);
//                    editor.commit();
//                }else{
//                    editor.putString("imgurl1", data);
//                    editor.commit();
//                }

                //       Picasso.with(CourseDetailsActivity.this).load(Uri.parse(data)).into(show_camera_iv);//加载图片
//                LogUtils.e("上传图片", data);
            }
        });

    }*/



    //图片旋转
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        ;
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }
    /**
     * 图片按比例大小压缩方法
     *
     * @param image （根据Bitmap图片压缩）
     * @return
     */
    public static Bitmap compressScale(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        // 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //Log.i(TAG, w + "---------------" + h);
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        // float hh = 800f;// 这里设置高度为800f
        // float ww = 480f;// 这里设置宽度为480f
        float hh = 600f;
        float ww = 450f;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be; // 设置缩放比例
        // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return bitmap;
        //return bitmap;
    }

    //违章培训上传图片
    public void uploadFile(Context context, File faceImgFile, int type,String url) {
        HelpUtil.uploadFile(context, faceImgFile, type, new OSSUpFileListener() {

            @Override
            public void onSuccess(WriterBean bean) {
                String ossUrl=bean.getData().getObjectAcsUrl();
               /* SharedPreferences sp = getSharedPreferences("homefgt", Context.MODE_PRIVATE);
                int faceRecgMark =sp.getInt("faceRecgMark", 0);
                String photoUrl = sp.getString("personphotoUrl", "");*/
                SharedPreferences sp = getSharedPreferences("StaticData", Context.MODE_PRIVATE);
                int faceRecgMark =sp.getInt("faceRecgMark", 0);
                String photoUrl = sp.getString("personphotoUrl", "");
                if(faceRecgMark==0){
                    saveVoidImg(ossUrl,url,faceRecgMark);
                }else{
                    compareFace(ossUrl,photoUrl,faceRecgMark,url);
                }
            }

            @Override
            public void onFail(String msg, WriterBean bean) {

            }

        });
    }

    public void saveVoidImg(String ossUrl,String imgUrl,int faceRecgMark){
        JSONObject js_request = new JSONObject();//服务器需要传参的json对象
        try {
            js_request.put("url", ossUrl);//根据实际需求添加相应键值对
            js_request.put("userId", userId);
            js_request.put("uvtcSn", uvtSn.toString());//根据实际需求添加相应键值对
            js_request.put("snapTime", snapTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams(AppInterfaceConfig.BASE_URL + "course/userVtcPhoto/add");
        params.setAsJsonContent(true);
        params.setBodyContent(js_request.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.e("测试", "onSuccess: "+result );
                if(faceRecgMark==0){
                    EventBus.getDefault().post(new MessageEvent(true, ossUrl, imgUrl,0, 0, "上传成功"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtils.e("测试", "onCancelled: " );
            }

            @Override
            public void onFinished() {
                LogUtils.e("测试", "onFinished: " );
            }
        });
    }

    public void compareFace(String imgPath, String headImg, int faceRecgMark, final String url) {
        JSONObject js_request = new JSONObject();//服务器需要传参的json对象
        try {
            js_request.put("imgPath", imgPath);//根据实际需求添加相应键值对
            js_request.put("headImg", headImg);
            js_request.put("faceRecgMark", faceRecgMark);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams(AppInterfaceConfig.BASE_URL + "app/compareFace");
        params.setAsJsonContent(true);
        params.setBodyContent(js_request.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                CompareFaceBean bean=JSON.parseObject(result,CompareFaceBean.class);
                EventBus.getDefault().post(new MessageEvent(bean.isResult(), bean.getData(), url, bean.getCode(), faceRecgMark, bean.getMsg()));
                if(bean.isResult()){
                    saveVoidImg(imgPath,url,faceRecgMark);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                EventBus.getDefault().post(new MessageEvent(false, "", url, 4, faceRecgMark,"请确保拍照面部完整，五官清晰，如您多次人脸失败，请在“我的”中检查您的个人头像是否正常且且清晰。"));
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}